const dayjs = require('dayjs');
const config = require('./config');

const baseUrl = 'http://111.202.113.148:18089';
const loginUrl = `${baseUrl}/zentao/user-login.html`;

module.exports = {
  browserArgs: [
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-dev-shm-usage',
    '--disable-accelerated-2d-canvas',
    '--no-first-run',
    '--no-zygote',
    '--disable-gpu',
  ],
  delay: (time) => new Promise((resolve) => setTimeout(resolve, time)),
  chunk: (arr, size) => {
    const result = [];

    for (let i = 0; i < arr.length; i += size) {
      result.push(arr.slice(i, i + size));
    }

    return result;
  },
  login: async (page) => {
    try {
      page.on('dialog', () => {
        console.log('🚀🔥✨登录信息错误');
        process.exit(1);
      });

      await page.goto(loginUrl);
      await page.type('#account', config.USERNAME, {
        delay: 20,
      });
      await page.type('[name="password"]', config.PASSWORD, {
        delay: 20,
      });
      await page.check('#keepLoginon');
      await page.click('#submit');
      await page.waitForURL(`${baseUrl}/zentao/my/`);
    } catch (error) {
      console.log('🚀🔥✨登录失败', error);
    }
  },
  getTaskLinks: async (page) => {
    await page.goto(`${baseUrl}/zentao/my-task-finishedBy.html`, {
      waitUntil: 'domcontentloaded',
    });
    await page.click('text=/每页 \\d+ 项 /i');
    await page.locator(`[data-size="${config.PAGE_SIZE}"]`).click();

    const trs = await page.$$('tbody tr');
    const links = await Promise.all(
      trs.map(async (tr) => {
        const $link = await tr.$('.c-name a');
        const $label = await tr.$('.label:has-text("子")');
        if ($label) {
          return null;
        }

        return $link.getAttribute('href');
      })
    );
    const validLinks = links.filter(Boolean);

    return validLinks;
  },

  getHours: async (page, link) => {
    try {
      await page.goto(`${baseUrl}${link}`, {
        waitUntil: 'domcontentloaded',
      });
      await page.locator('text=任务的一生').click();
      const $complete = await page.locator('th:has-text("由谁完成") + td');
      const text = await $complete.innerText();
      const [, date] = text.split(' 于 ');
      const match = config.MATCH_MONTHS.some(
        (month) => dayjs(date).format('YYYY-MM') === month
      );

      if (match) {
        const $consume = await page.locator('th:has-text("总计消耗") + td');
        const title = await page.$eval(
          '#legendBasic > table > tbody > tr:nth-child(1) > td > a',
          (el) => {
            return el.innerText;
          }
        );
        const text = await $consume.innerText();
        const hours = parseFloat(text.split('工时')[0]);
        return {
          title,
          hours,
        };
      }

      return null;
    } catch (error) {
      console.log('🚀🔥✨任务页面获取工时失败', error);
      return null;
    }
  },
  getWorkerDayCount: () => {
    let now = new Date();
    let start = new Date(now.getFullYear(), now.getMonth(), 1); // 当月初
    let workdays = 0;

    for (let day = start; day <= now; day.setDate(day.getDate() + 1)) {
      let dayOfWeek = day.getDay();
      if (dayOfWeek > 0 && dayOfWeek < 6) {
        // 周一到周五
        workdays++;
      }
    }

    return workdays;
  },
};
